package com.carleasoft.mps.data.redis.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * Jedis整合spring配置,暂无高可用需求，用一次性哈希分片集群思维
 * @author: haoyi
 */
@Configuration
public class JedisConfig {

    @Value("${spring.redis.maxTotal:50}")
    private Integer maxTotal;

    @Value("${spring.redis.maxIdle:20}")
    private Integer maxIdle;

    @Value("${spring.redis.maxWaitMillis:1000}")
    private Long maxWaitMillis;

    @Value("${spring.redis.host:127.0.0.1}")
    private String redisHost;

    @Value("${spring.redis.port:6379}")
    private Integer redisPost;

    @Value("${spring.redis.connectionTimeout:6000}")
    private Integer connectionTimeout;

    @Value("${spring.redis.password:carlea2020}")
    private String password;

    @Value("${spring.redis.database:0}")
    private Integer db;

    @Bean(name = "jedisPoolConfig")
    public JedisPoolConfig jedisPoolConfig(){
        System.out.println("#####$$4初始化 jedis");
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);
        return jedisPoolConfig;
    }

    @Bean(name = "jedisPool")
    public JedisPool  shardedJedisPool(@Qualifier("jedisPoolConfig") JedisPoolConfig jedisPoolConfig){

        JedisPool  jedisPool = new JedisPool(jedisPoolConfig,redisHost,redisPost,connectionTimeout,password,db);

        return jedisPool;
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        // redis 消息订阅(监听)者容器
        RedisMessageListenerContainer messageListenerContainer = new RedisMessageListenerContainer();
        messageListenerContainer.setConnectionFactory(redisConnectionFactory);
        return messageListenerContainer;
    }
}
